"""CopyRight(C) From WangShiheng"""
# Author: WangShiheng
# Package
import datetime
import os
import time
from util.base.LOGGER.LOG import LOGGER

import cv2
import numpy as np
import win32gui
from PIL import ImageGrab


def get_name_from_window(LOGGER=LOGGER):
    while True:
        WindowScreen = ImageGrab.grab()
        WindowScreen = np.array(WindowScreen.getdata(), np.uint8).reshape(WindowScreen.size[1], WindowScreen.size[0], 3)
        r, g, b = cv2.split(WindowScreen)
        cv2.merge([b, g, r], WindowScreen)
        point = win32gui.GetCursorPos()
        hwnd = win32gui.WindowFromPoint(point)
        rect = win32gui.GetWindowRect(hwnd)
        y1, x1, y2, x2 = rect

        paint_Border(WindowScreen, x1, x2, y1, y2)
        cv2.imwrite(r'.\{}.jpg'.format(datetime.datetime.now()), WindowScreen)

        time.sleep(0.5)


def paint_Border(img, x1, x2, y1, y2):
    # left + right
    print(x1, x2, y1, y2)
    for i in range(max(x1 - 7, 0), min(x2 + 7, img.shape[1] - 2)):
        img[i, y1 - 7] = [255, 255, 255]
        img[i, y2 + 3: y2 + 7] = [255, 255, 255]

    # top + bottom
    for i in range(y1 - 7, y2 + 7):
        img[x1 - 7: x1 - 3, i] = [255, 255, 255]
        img[x2 + 3: x2 + 7, i] = [255, 255, 255]


if __name__ == '__main__':
    try:
        get_name_from_window()
    except KeyboardInterrupt:
        print(os.getpid())
        print(os.getcwd())

# def get_Window_PID(point, LOGGER=logger):
#     try:
#         hwnd = win32gui.WindowFromPoint(point)
#         # p_name = win32gui.GetWindowText(hwnd)
#         # _, p_id = win32process.GetWindowThreadProcessId(hwnd)
#         # print(p_name + '  ' + str(p_id))
#         return p_id
#     except Exception as e:
#         LOGGER.warning("win32获取窗体信息失败 error")
#         # raise e
#     except KeyboardInterrupt as e:
#         LOGGER.error("KeyBoardError")
#         sys.exit()
